<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        title="注意！只允许为第三级分类设置相关参数"
        type="warning"
        show-icon
      >
      </el-alert>
      <el-row :gutter="10" class="selectCate">
        <span> 选择商品分类： </span>
        <el-cascader
          v-model="cateArr"
          :props="cateObj"
          :options="cateListData"
          clearable
          @change="handleChange"
        ></el-cascader>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" @click="addParams" :disabled="isBtnDisabled"
            >添加参数</el-button
          >
          <el-table :data="tableData">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="deleteTag(index, scope.row)"
                  class="tagStyle"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.expandInputVisible"
                  v-model="scope.row.expandInputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="editParamsClick(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="delParamsClick(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" @click="addParams" :disabled="isBtnDisabled"
            >添加属性</el-button
          >
          <el-table :data="tableData">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="deleteTag(index, scope.row)"
                  class="tagStyle"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.expandInputVisible"
                  v-model="scope.row.expandInputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="editParamsClick(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="delParamsClick(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <el-dialog
        :title="'添加' + cateName"
        :visible.sync="dialogVisible"
        width="40%"
        @close="closeAddDialog"
      >
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="100px"
        >
          <el-form-item prop="attr_name" :label="cateName">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addClick">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog
        :title="'修改' + cateName"
        :visible.sync="editDialogVisible"
        width="40%"
        @close="closeEditDialog"
      >
        <el-form
          :model="editForm"
          :rules="editFormRules"
          ref="editFormRef"
          label-width="100px"
        >
          <el-form-item prop="attr_name" :label="cateName">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancleEditDialog">取 消</el-button>
          <el-button type="primary" @click="editClick">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      addParamsDialog: false,
      cateListData: [],
      cateArr: [],
      cateObj: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
        checkStrictly: true
      },
      activeName: 'many',
      tableData: [],
      dialogVisible: false,
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入信息', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      },
      // 编辑的对话框
      editDialogVisible: false,
      editForm: {
        attr_name: ''
      },
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入信息', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getCascaderData()
    // 根据级联选择器数组的长度控制添加按钮的禁用状态 方法一
    // if (!this.cateArr.length) {
    //   this.addParamsDialog = true
    // }
  },
  computed: {
    cateId() {
      if (this.cateArr.length === 3) {
        return this.cateArr[2]
      } else {
        return null
      }
    },
    cateName() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    },
    // 根据级联选择器数组的长度控制添加按钮的禁用状态 方法二
    isBtnDisabled() {
      if (this.cateArr.length !== 3) {
        return true
      }
      return false
    }
  },
  // 根据级联选择器数组的长度控制添加按钮的禁用状态 方法一
  // watch: {
  //   cateArr(v) {
  //     if (v.length === 3) {
  //       this.addParamsDialog = false
  //     }
  //   }
  // },
  methods: {
    deleteTag(index, row) {
      row.attr_vals.splice(index, 1)
      this.saveTags(row)
    },
    saveTags(row) {
      const saveObj = {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      }
      this.$http
        .put(`categories/${this.cateId}/attributes/${row.attr_id}`, saveObj)
        .then((res) => {
          console.log(res)
          this.$message.success(res.data.meta.msg)
        })
    },
    handleInputConfirm(row) {
      if (row.expandInputValue.trim().length === 0) {
        row.expandInputValue = ''
        row.expandInputVisible = false
        return
      }
      row.attr_vals.push(row.expandInputValue.trim())
      row.expandInputValue = ''
      row.expandInputVisible = false
      this.saveTags(row)
    },
    showInput(row) {
      row.expandInputVisible = true
      // $nextTick方法的作用, 就是当页面上的元素被重新渲染之后,才会指定回调函数中的代码
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    cancleEditDialog() {
      this.$refs.editFormRef.resetFields()
      this.editDialogVisible = false
    },
    delParamsClick(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$http
            .delete(`categories/${row.cat_id}/attributes/${row.attr_id}`)
            .then((res) => {
              this.getParamsData()
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.editDialogVisible = false
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    editClick() {
      this.$refs.editFormRef.validate((valid) => {
        if (valid) {
          const obj = {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          }
          this.$http
            .put(
              `categories/${this.editForm.cat_id}/attributes/${this.editForm.attr_id}`,
              obj
            )
            .then((res) => {
              this.$message.success('修改成功')
              this.getParamsData()
              this.editDialogVisible = false
              console.log(res)
            })
          this.editDialogVisible = false
        } else {
          this.$message.error('请输入正确信息')
        }
      })
    },
    editParamsClick(row) {
      this.$http
        .get(`categories/${row.cat_id}/attributes/${row.attr_id}`)
        .then((res) => {
          this.editForm.attr_name = res.data.data.attr_name
          this.editForm.attr_id = res.data.data.attr_id
          this.editForm.cat_id = res.data.data.cat_id
        })
      this.editDialogVisible = true
    },
    closeEditDialog() {},
    addClick() {
      this.$refs.addFormRef.validate((valid) => {
        if (valid) {
          const obj = {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
          this.$http
            .post(`categories/${this.cateId}/attributes`, obj)
            .then((res) => {
              this.getParamsData()
              this.$message.success('添加' + this.cateName + '成功')
              this.dialogVisible = false
            })
        } else {
          this.$message.error('请输入必填信息')
        }
      })
      // this.dialogVisible = false
    },
    closeAddDialog() {
      this.$refs.addFormRef.resetFields()
    },
    addParams() {
      this.dialogVisible = true
    },
    handleClick() {
      this.getParamsData()
    },
    handleChange() {
      if (this.cateArr.length === 3) {
        this.getParamsData()
      } else {
        this.tableData = []
      }
    },
    getCascaderData() {
      this.$http.get('categories').then((res) => {
        this.cateListData = res.data.data
      })
    },
    getParamsData() {
      if (this.cateArr.length === 3) {
        this.$http
          .get(`categories/${this.cateId}/attributes`, {
            params: {
              sel: this.activeName
            }
          })
          .then((res) => {
            res.data.data.forEach((item) => {
              item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
              item.expandInputVisible = false
              item.expandInputValue = ''
            })
            this.tableData = res.data.data
            // if (this.activeName === 'many') {
            //   this.tableData = res.data.data
            // } else {
            //   this.tableData = res.data.data
            // }
          })
      } else {
        this.cateArr = []
      }
    }
  }
}
</script>

<style scoped>
.tagStyle {
  margin-right: 10px;
}
.input-new-tag {
  width: 100px;
}
</style>
